<?php
/**
 *
 *   User:King
 *   Date:2021/12/9 17:05
 */

namespace app\bank_api\controller;


use app\common\library\Integrate;
use app\common\model\Business;
use app\common\model\TicketAllocation;
use app\common\model\TicketTemplate;
use think\Db;
use think\Log;

class Ticket extends Base
{
    protected $noNeedRight = '*';

    /**
     * 获取银行业务
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function business(){
        if(!$this->staffinfo){
            $this->error('请检查员工是否被禁用');
        }
        $staff = $this->staffinfo;
        $business_where['admin_id'] = $staff['admin_id'];
//        if($staff['branch_id']){
//            $business_where['branch_id'] = $staff['branch_id'];
//        }
        $data = Business::where($business_where)->field('id,name,dec')->where('status',1)->order('sort desc')->select();
        $this->success('获取成功',$data);
    }

    public function info(){
        $this->onlyPost();
        if(!$this->staffinfo){
            $this->error('请检查员工是否被禁用');
        }
        $staff = $this->staffinfo;
        $code = $this->request->post('code');
        $ticket = \app\common\model\Ticket::where('code',$code)
            ->where('status',1)
            ->where('state',4)
            ->with([
                'template' => function($query){
                    $query->field('id,name,denomination,instructions,phone');
                },
                'printing' => function($query){
                    $query->field('id,expire_time,batch_no');
                },
            ])
            ->where('admin_id',$staff['admin_id'])
            ->where('branch_id',$staff['branch_id'])
            ->find();
        if(empty($ticket)){
            $this->error('无效的券');
        }
        $return_data = [
            'code' => $ticket->code,
            'name' => $ticket->template->name,
            'denomination' => $ticket->template->denomination,
            'instructions' => $ticket->template->instructions,
            'phone' => $ticket->template->phone,
            'expire_time' => $ticket->printing->expire_time,
        ];
        $this->success('获取成功',$return_data);
    }


    public function activate(){
        $this->onlyPost();
        if(!$this->staffinfo){
            $this->error('请检查员工是否被禁用');
        }
        $staff = $this->staffinfo;
        $code = $this->request->post('code');
        $business_id = $this->request->post('business_id');
        if(empty(Business::where(['id'=>$business_id,'admin_id'=>$staff['admin_id']])->find())){
            $this->error('业务不存在或被禁用');
        }
        $ticket = \app\common\model\Ticket::where('code',$code)
            // ->where('status',1)
            ->where('state',5)
            ->where('admin_id',$staff['admin_id'])
            ->where('branch_id',$staff['branch_id'])
            ->find();
        if(empty($ticket)){
            $this->error('此券无法激活或已激活');
        }
//        if($ticket->status != 1){
//            switch ($ticket->status){
//                case 2:
//                    $this->error('券已激活');
//                    break;
//                case 3:
//                    $this->error('券已核销');
//                    break;
//                case 4:
//                    $this->error('券已失效');
//                    break;
//                case 5:
//                    $this->error('券已禁用');
//                    break;
//            }
//        }

        $integrate = new Integrate();
        $res = $integrate->activate(['code_number' => $code]);
        if($res['code']  != 1){
            $this->error($res['msg']);
        }




        $ticket->business_id = $business_id;
        $ticket->state = 5;
        $ticket->status = 2;
        $ticket->staff_id = $staff['id'];
        $ticket->activate_time = time();
        $res = $ticket->save();
        if(!$res){
            $this->error('激活失败');
        }
        $this->success('激活成功');
    }

    public function activate_list(){
        $this->onlyPost();
        if(!$this->staffinfo){
            $this->error('请检查员工是否被禁用');
        }
//        $limit = $this->request->post('limit',10);
//        $page = $this->request->post('page',1);
        $business_id = $this->request->post('business_id',null);
        $ticket_template_id = $this->request->post('ticket_template_id',null);
        $start_time = $this->request->post('start_time',null);
        $end_time = $this->request->post('end_time',null);
        $where['staff_id'] = $this->staffinfo['id'];
        if($business_id)$where['business_id'] = $business_id;
        if($ticket_template_id)$where['ticket_template_id'] = $ticket_template_id;


        $ticket = \app\common\model\Ticket::where($where)
            ->with([
                'template' => function($query){
                    $query->field('id,name,denomination,instructions,phone');
                },
                'business' => function($query){
                    $query->field('id,name');
                },
            ]);
        if($start_time)   $ticket->where('activate_time','>=',$start_time);
        if($end_time)     $ticket->where('activate_time','<=',$end_time);

            $data = $ticket
            ->order('activate_time DESC')
//            ->limit($page>0?($page-1)*$limit:0,$limit)
            ->limit($this->page,$this->limit)
            ->select();
        if(empty($data)){
            $this->success('暂无激活数据',[]);
        }
        $return_data= [];
        foreach ($data as $k=>$item){
            $return_data[$k] = [
                'code' => $item->code,
                'activate_time' => date('Y-m-d H:i',$item->activate_time),
                'business_name' => isset($item->business->name)?$item->business->name:'',
                'name' => $item->template->name,
                'denomination' => $item->template->denomination,
            ];
        }
        $total = \app\common\model\Ticket::where($where)->field('count(id) as total,sum(gold_score) as total_score')->find();

        $this->success('获取成功',['count' => $total->total,'total_score' => $total->total_score,'list'=>$return_data]);
    }

    public function template(){
        if(!$this->staffinfo){
            $this->error('请检查员工是否被禁用');
        }
        $category = $this->request->post('category',1);
        if($category == 2){
            $ticket_template_ids = \app\common\model\Ticket::where([
                    'admin_id' => $this->staffinfo['admin_id'],
                    'category' => $category,
                    'state' => 4
                ])
                ->whereIn('status',[1,2])
                ->group('ticket_template_id')
                ->column('ticket_template_id');
            $data = TicketTemplate::whereIn('id',$ticket_template_ids)
                ->field('id,name,denomination')
                ->select();
        }else{
            $data = TicketTemplate::where(['admin_id' => $this->staffinfo['admin_id'],'category' => $category])
                ->field('id,name,denomination')
                ->select();
        }
        Log::info('输入：'.json_encode($data));
        $this->success('获取成功',$data);
    }

    /**
     * 领取积分券
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function grant(){
        $this->onlyPost();
        if(!$this->staffinfo){
            $this->error('请检查员工是否被禁用');
        }
        $template_id = $this->request->post('template_id',null);
        $business_id = $this->request->post('business_id');
        if(!$template_id || !$business_id){
            $this->error('参数错误');
        }
        //检查该支行是否还有可发券
        $allocation = TicketAllocation::where('branch_id',$this->staffinfo['branch_id'])
            ->where('template_id',$template_id)
            ->find();
        if(empty($allocation) || $allocation->surplus<=0){
            $this->error('暂无可用积分券');
        }

        //先获取已激活但未领取的积分券
        $ticket = \app\common\model\Ticket::where([
                'user_id' => null,
                'admin_id'=>$this->staffinfo['admin_id'],
                'status' => 2,
                'staff_id' => $this->staffinfo['id'],
                'category' =>2,
                'ticket_template_id' => $template_id
            ])
            ->find();
        if(empty($ticket)){
            $ticket = \app\common\model\Ticket::where([
                    'admin_id'=>$this->staffinfo['admin_id'],
                    'status' => 1,
                    'state' => 4,
                    'category' =>2,
                    'ticket_template_id' => $template_id
                ])
                ->find();
        }
        if(empty($ticket)){
            $this->error('暂无积分券');
        }
        if($ticket->status == 1){
            $integrate = new Integrate();
            $res = $integrate->activate(['code_number' => $ticket->code]);
            if($res['code']  != 1){
                $this->error($res['msg']);
            }
        }
        $time = time();
        $ticket->business_id = $business_id;
        $ticket->state = 5;
        $ticket->status = 2;
        $ticket->grant_time = $time;
        $ticket->activate_time = $time;
        $ticket->branch_id = $this->staffinfo['branch_id'];
        $ticket->staff_id = $this->staffinfo['id'];
        $ticket->updatetime = $time;
        $res = $ticket->save();
        if(!$res){
            $this->error('领取失败');
        }
        TicketTemplate::where('id',$ticket->ticket_template_id)->setDec('await_grant');
        $this->success('领取成功',['url' => 'https://cs.pdsyun.com/coupon?code_number='.$ticket->code]);
    }
}
